package com.alibaba.csp.sentinel.dashboard.rule.database.base;

import com.alibaba.csp.sentinel.dashboard.rule.database.enums.DatabaseRuleEnums;
import com.alibaba.csp.sentinel.dashboard.repository.dao.SqlHelper;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

/**
 *
 */
@Component
public abstract class BaseDatabaseRulePublisher implements DynamicRulePublisher {

    @Override
    public void publish(String app, Object rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        DatabaseRuleEnums dataId = getDataId();

        saveRulesToDatabase(app, dataId, rules);
    }

    protected abstract DatabaseRuleEnums getDataId();

    /**
     * 存规则到db
     *
     * @param appName
     * @param dataId
     * @return
     */
    protected void saveRulesToDatabase(String appName, DatabaseRuleEnums dataId, Object rules) {

        SqlHelper.ExecSql("REPLACE INTO `cc_sentinel_rule`\n" +
                "(`rule_id`,\n" +
                "`rule_name`,\n" +
                "`rule_type`,\n" +
                "`app_name`,\n" +
                "`content`)\n" +
                "VALUES\n(" +
                "\n?," +
                "\n?," +
                "\n?," +
                "\n?," +
                "\n?" +
                ");", null, dataId.getName(), dataId.getCode(), appName, JSON.toJSONString(rules));
    }
}
